package com.icim.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.icim.service.IHeartBeatService;
import com.icim.util.DBUtil;

public class HeartBeatService implements IHeartBeatService {
	private Logger logger = Logger.getLogger(HeartBeatService.class);
	@Resource
	DBUtil dBUtil;

	public boolean checkRabbitMQ() {
		//TODO:
		return true;
	}

	public boolean checkDB() {
		/**
		 * check connection is valid
		 */
		boolean connectionIsValid = false;
		Statement stmt = null;
		String sql = "SELECT 1";
		Connection connection = null;
		try {
			 dBUtil.openConnection();
			stmt = connection.createStatement();
			stmt.executeQuery(sql);
			connectionIsValid = true;
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			connectionIsValid = false;
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				logger.info("鍙戦�蹇冭烦鏃�鍏抽棴Statement鎶ラ敊" + e.getMessage());
				e.printStackTrace();
			}

		}
		return connectionIsValid;

	}

	public boolean sendHttpCall() {
		//TODO:
		return true;
	}

	@Override
	public void sendHeartBeat() {
		boolean isSuccess = false;
		try {
			isSuccess = checkRabbitMQ();
			if (!isSuccess) {
				return;
			}
//			isSuccess = checkDB();
//			if (!isSuccess) {
//				return;
//			}
			isSuccess = sendHttpCall();
			if (!isSuccess) {
				return;
			}
			logger.info("Send Heart Beat .............................");
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("connect db or rabbitmq error" + e.getMessage());
		}

	}

}
